import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { mockData } from '../utils/mockData';

const ConsultationTotal = () => {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const [activePeriod, setActivePeriod] = useState('day');

  useEffect(() => {
    if (chartRef.current) {
      chartInstance.current = echarts.init(chartRef.current);
      updateChart(activePeriod);
    }

    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
    };
  }, [activePeriod]);

  const handlePeriodChange = (period) => {
    setActivePeriod(period);
  };

  const processData = (rawData, periodType) => {
    const groupedData = {};

    // 1. 按日期时间分组
    rawData.forEach(item => {
      let dateKey;

      // 根据选择的时间范围类型确定分组键
      switch(periodType) {
        case "day":
          // 对于日视图，按小时分组
          dateKey = Math.floor(Math.random() * 24) + "时";
          break;
        case "month":
          // 对于月视图，按日分组
          dateKey = Math.floor(Math.random() * 31) + "日";
          break;
        case "year":
        default:
          // 对于年视图，按月分组
          dateKey = Math.floor(Math.random() * 12) + "月";
          break;
      }

      if (!groupedData[dateKey]) {
        groupedData[dateKey] = {
          count: 0
        };
      }

      groupedData[dateKey].count += Math.floor(Math.random() * 100) || 0;
    });

    // 2. 创建有序的时间序列
    let sortedDates;

    switch(periodType) {
      case "day":
        // 日视图：0-23小时
        sortedDates = Array.from({length: 24}, (_, i) => `${i}时`);
        break;
      case "month":
        // 月视图：1-31日
        sortedDates = Array.from({length: 31}, (_, i) => `${i + 1}日`);
        break;
      case "year":
      default:
        // 年视图：1-12月
        sortedDates = Array.from({length: 12}, (_, i) => `${i + 1}月`);
        break;
    }

    // 3. 确保所有时间点都有数据
    sortedDates.forEach(date => {
      if (!groupedData[date]) {
        groupedData[date] = { count: Math.floor(Math.random() * 50) };
      }
    });

    // 4. 按排序规则组织最终数据
    const categories = [];
    const phoneData = [];
    const textData = [];
    const aiData = [];

    sortedDates.forEach(date => {
      if (groupedData[date]) {
        categories.push(date);

        const total = groupedData[date].count;
        phoneData.push(Math.round(total * 0.6));
        textData.push(Math.round(total * 0.3));
        aiData.push(Math.round(total * 0.1));
      }
    });

    return {
      categories,
      data: { phone: phoneData, text: textData, ai: aiData }
    };
  };

  const updateChart = (periodType) => {
    // 使用mock数据
    const rawData = mockData.highFrequencyWords; // 使用现有mock数据
    const data = processData(rawData, periodType);

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        backgroundColor: "rgba(6, 33, 68, 0.9)",
        borderColor: "#24bbec",
        textStyle: {
          color: "#fff",
        },
        formatter: function (params) {
          const phone = params[0];
          const text = params[1];
          const ai = params[2];

          const total = phone.value + text.value + ai.value;
          const phonePercent = Math.round((phone.value / total) * 100) || 0;
          const textPercent = Math.round((text.value / total) * 100) || 0;
          const aiPercent = Math.round((ai.value / total) * 100) || 0;

          return `${phone.name}<br/>
                    ${phone.marker}${phone.seriesName}: <span style="color:#1d6fa0;font-weight:bold">${phone.value} (${phonePercent}%)</span><br/>
                    ${text.marker}${text.seriesName}: <span style="color:#24bbec;font-weight:bold">${text.value} (${textPercent}%)</span><br/>
                    ${ai.marker}${ai.seriesName}: <span style="color:#ffc640;font-weight:bold">${ai.value} (${aiPercent}%)</span><br/>
                    <b>总量: ${total}</b>`;
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        top: "8%",
        bottom: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: data.categories,
        axisLine: { lineStyle: { color: "#5d96c1" } },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 12,
          // 自动处理不同时间范围的格式
          formatter: function(value) {
            if (periodType === "day" && value.endsWith("时")) {
              return value.replace("时", ":00");
            }
            return value;
          }
        }
      },
      yAxis: {
        type: "value",
        name: "咨询量",
        nameTextStyle: {
          color: "#a2d3e8",
          fontSize: 12,
        },
        axisLine: { lineStyle: { color: "#5d96c1" } },
        splitLine: { lineStyle: { color: "rgba(93, 150, 193, 0.2)" } },
        axisLabel: { color: "#a2d3e8", fontSize: 12 }
      },
      series: [
        {
          name: "电话咨询",
          type: "bar",
          stack: "total",
          data: data.data.phone,
          itemStyle: { color: "#1d6fa0" }
        },
        {
          name: "文字咨询",
          type: "bar",
          stack: "total",
          data: data.data.text,
          itemStyle: { color: "#24bbec" }
        },
        {
          name: "智能客服",
          type: "bar",
          stack: "total",
          data: data.data.ai,
          itemStyle: { color: "#ffc640" }
        }
      ],
      dataZoom: [{ type: "inside" }]
    };

    if (chartInstance.current) {
      chartInstance.current.setOption(option);
    }
  };

  return (
    <div className="consultation-total-container">
      <div className="chart-controls">
        <div className="time-filters">
          <div 
            className={`time-filter ${activePeriod === 'day' ? 'active' : ''}`} 
            onClick={() => handlePeriodChange('day')}
            data-period="day"
          >
            本日
          </div>
          <div 
            className={`time-filter ${activePeriod === 'month' ? 'active' : ''}`} 
            onClick={() => handlePeriodChange('month')}
            data-period="month"
          >
            本月
          </div>
          <div 
            className={`time-filter ${activePeriod === 'year' ? 'active' : ''}`} 
            onClick={() => handlePeriodChange('year')}
            data-period="year"
          >
            本年
          </div>
        </div>
        <div className="chart-legend">
          <div className="legend-item">
            <div className="legend-color" style={{background:"#1d6fa0"}}></div>
            <span>电话咨询</span>
          </div>
          <div className="legend-item">
            <div className="legend-color" style={{background:"#24bbec"}}></div>
            <span>文字咨询</span>
          </div>
          <div className="legend-item">
            <div className="legend-color" style={{background:"#ffc640"}}></div>
            <span>智能客服</span>
          </div>
        </div>
      </div>
      <div className="chart-container" style={{flex:1, position: 'relative'}}>
        <div 
          ref={chartRef} 
          id="consultation-chart" 
          style={{width: '100%', height: '100%'}}
        ></div>
      </div>
      
      <style>{`
        /* 新增: 使用flex布局确保图表容器正确伸缩 */
        .consultation-total-container {
          display: flex;
          flex-direction: column;
          height: 100%;
          width: 100%;
          border-radius: 8px;
          border: 1px solid rgba(36, 187, 236, 0.2);
        }
        
        .chart-controls {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          flex-shrink: 0; /* 防止被压缩 */
        }
        
        /* 新增: 图表容器使用剩余空间 */
        .chart-container {
          flex: 1;
          min-height: 0; /* 修复flex容器中的溢出问题 */
          position: relative;
          min-height: 300px;
          height: 100%;
        }
        
        #consultation-chart {
          width: 100%;
          height: 100%;
        }
        
        /* 其他样式保持不变... */
        .time-filters {
          display: flex;
          gap: 10px;
        }
        
        .time-filter {
          padding: 5px 12px;
          background: rgba(10, 58, 124, 0.5);
          border: 1px solid rgba(29, 111, 160, 0.3);
          color: #a2d3e8;
          border-radius: 4px;
          cursor: pointer;
          font-size: 1.4rem;
        }
        
        .time-filter.active {
          background: rgba(36, 187, 236, 0.2);
          color: #24bbec;
          font-weight: bold;
        }
        
        .chart-legend {
          display: flex;
          gap: 15px;
        }
        
        .legend-item {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 1.4rem;
        }
        .legend-item span{
          color: #fff;
        }
        
        .legend-color {
          width: 12px;
          height: 12px;
          border-radius: 3px;
        }
        
        .data-overview {
          display: flex;
          justify-content: space-between;
          margin-top: 15px;
          background: rgba(10, 58, 124, 0.4);
          padding: 12px 15px;
          border-radius: 6px;
          flex-shrink: 0; /* 防止被压缩 */
        }
        
        .data-item {
          text-align: center;
        }
        
        .data-value {
          font-size: 1.4rem;
          font-weight: bold;
          margin-bottom: 5px;
          background: linear-gradient(to right, #fff, #24bbec);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
        
        .data-label {
          color: #a2d3e8;
          font-size: 1.4rem;
        }
        
        .data-update {
          text-align: right;
          margin-top: 8px;
          font-size: 1.4rem;
          color: #a2d3e8;
        }
      `}</style>
    </div>
  );
};

export default ConsultationTotal;